package com.example.withroadlogistics.Clockin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapLayer;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.withroadlogistics.R;
import com.example.withroadlogistics.model.Blog;
import com.example.withroadlogistics.model.RouteMap;
import com.example.withroadlogistics.until.HttpCallbackListener;
import com.example.withroadlogistics.until.HttpUtil;
import com.example.withroadlogistics.until.MySharedPreferences;
import com.example.withroadlogistics.until.constant;
import com.example.withroadlogistics.weibo.weibosend;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 时时定位上传
 */
public class TransportSceneActivity extends Activity{
    private String TAG = "ifu25";
    private LocationClient mLocClient;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    // 是否首次定位
    boolean isFirstLoc = true;//首次的话，加载原先地图图层再实行定位模式
    private BitmapDescriptor bitmapA = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);
    private Marker mMarker;
    private String originAddress = constant.url+"routemap/addroutemap";//添加连接
    //    Handler是Android SDK来处理异步消息的核心类。
//    子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";

            if ("OK".equals(msg.obj.toString())){//获取后台返回来的msg
                result = "success";
            }else if ("Wrong".equals(msg.obj.toString())){
                result = "fail";
            }else {
                String data = msg.obj.toString();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (code.equals("0")) {
                        //web端返回的json code data
                        Log.i(TAG, "handleMessage: wen端返回的json"+code+data+result);
                        //通过Bundle封装数据
                        Bundle bundle = new Bundle();
                        // bundle.putString("data", result);//data是通过后台返回数值进行判断，弹窗
                        //通过Intent控制Activity跳转
                        Toast.makeText(TransportSceneActivity.this, "发送成功", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(TransportSceneActivity.this, result, Toast.LENGTH_LONG).show();//失败提示
                        Toast.makeText(TransportSceneActivity.this, "发送失败，请查看你的定位连接", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(TransportSceneActivity.this, "系统异常请重试", Toast.LENGTH_LONG).show();
                }
            }

        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.background_locate);

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        final MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        RadioGroup group = (RadioGroup)findViewById(R.id.radioGroup);
        RadioGroup.OnCheckedChangeListener radioButtonListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.defaulticon) {
                    // 传入null则，恢复默认图标
                    mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
                }
                if (checkedId == R.id.customicon) {
                    int accuracyCircleFillColor = 0xAAFFFF88;
                    int accuracyCircleStrokeColor = 0xAA00FF00;
                    // 修改为自定义图层
                    BitmapDescriptor currentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
                    mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, currentMarker,
                            accuracyCircleFillColor, accuracyCircleStrokeColor));
                    currentMarker.recycle();
                }
            }
        };
        group.setOnCheckedChangeListener(radioButtonListener);
        // 定位初始化
        initLocation();
        // 地图定位图标点击事件监听
        mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {
            @Override
            public boolean onMyLocationClick() {
                Toast.makeText(TransportSceneActivity.this,"点击定位图标", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Toast.makeText(TransportSceneActivity.this,"点击Marker图标", Toast.LENGTH_SHORT).show();
                return true;
            }
        });


    }

    /**
     * 定位初始化
     */
    public void initLocation(){
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        TransportSceneActivity.MyLocationListenner myListener = new TransportSceneActivity.MyLocationListenner();
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();

        // 打开gps
        option.setOpenGps(true);
        // 设置坐标类型
        option.setCoorType("bd09ll");
        option.setScanSpan(3000);//3000毫秒定位一次
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 添加marker
     *
     * @param latLng 经纬度
     */
    public void addMarker(LatLng latLng){
        if (latLng.latitude == 0.0 || latLng.longitude == 0.0){
            return;
        }
        MarkerOptions markerOptionsA = new MarkerOptions().position(latLng).yOffset(30).icon(bitmapA).draggable(true);
        mMarker = (Marker) mBaiduMap.addOverlay(markerOptionsA);

    }

    /**
     * 切换指定图层的顺序
     */
    public void switchLayerOrder(View view){
        if (mBaiduMap == null){
            return;
        }
        mBaiduMap.switchLayerOrder(MapLayer.MAP_LAYER_LOCATION, MapLayer.MAP_LAYER_OVERLAY);
    }

    /**
     * 开启后台定位模式
     */
    public void setLayerClickable(View view){


    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // MapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
//             if (location.getLocType() == BDLocation.TypeGpsLocation) {//判断是否是GPS移动获取定位
//                 final double jingdu = location.getLatitude();
//                 final double weidu = location.getLongitude();
//                 Log.i("精度1",jingdu+"");
//                 Log.i("纬度1",weidu+"");
//            Float speed =location.getSpeed();
//                Log.i("速度1",speed+"m/s");
//              }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())// 设置定位数据的精度信息，单位：米
                    .direction(location.getDirection()) // 此处设置开发者获取到的方向信息，顺时针0-360
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .speed(location.getSpeed())//获取速度
                    .build();
            //只有打开gps才是gps定位才有速度变化，否则就是网路定位，无速度
            final double latitude = location.getLatitude();//可静止获取定位
            final double longitude = location.getLongitude();
            Float speed = location.getSpeed();
            String routemaptime =location.getTime();
            Log.i("当前经度",longitude+"");
            Log.i("当前纬度",latitude+"");
            Log.i("当前速度",speed+"");
            Log.i("当前时间",routemaptime+"");

            //获取传递参数，将参数放在哈希表里存储
            if (!isInputValid()){
                return;
            }
            HashMap<String, String> params = new HashMap<String, String>();
            params.put(RouteMap.LATITUDE,String.valueOf(latitude));
            params.put(RouteMap.LONGITUDE, String.valueOf(longitude));
            params.put(RouteMap.SPEED, String.valueOf(speed));
            params.put(RouteMap.ROUTEMAPTIME,routemaptime);


            try {
                String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);
                HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                    @Override
                    public void onFinish(String response) {
                        Message message = new Message();
                        message.obj = response;
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void onError(Exception e) {
                        Message message = new Message();
                        message.obj = e.toString();
                        mHandler.sendMessage(message);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 设置定位数据, 只有先允许定位图层后设置数据才会生效
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(latLng).zoom(18.0f);//设置地图级别，级别越大1-19级，精度越大
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                addMarker(latLng);
            }
            if (mMarker != null){
                mMarker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
            }
        }

    }

    private boolean isInputValid() {
        //检查用户输入的合法性，这里暂且默认用户输入合法
        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();
        // 在activity执行onResume时必须调用mMapView. onResume ()
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在activity执行onPause时必须调用mMapView. onPause ()
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bitmapA.recycle();
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        // 在activity执行onDestroy时必须调用mMapView.onDestroy()
        mMapView.onDestroy();
    }
}
